package com.douwong.student.socket;

import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;

import com.douwong.student.model.TcpPacket;


/**
 * @author Tab.lv
 * @category 交互消息队列，使用非UI线程的Handler操作MQ
 */
public class MessageQueue extends HandlerThread {
	

	private MqHandler mqHandler=null;
	private static MessageQueue mq=null;
	private Context context;
	public MessageQueue(String name, Context context) {
		super(name);
		this.context=context;
	}
	
	public static MessageQueue getInstance(Context context){
		if(mq==null){
			mq=new MessageQueue("MessageQueue",context);
			new Thread(mq).start();

		}		
		return mq;
	}
	@Override
	public void run() {			
		Looper.prepare();
		mqHandler=new MqHandler(Looper.myLooper());
		Looper.loop();
	}	
	
	public MqHandler getLwHandler(){
		
		if(mqHandler==null){
			//第一次使用在线程中创建mqHandler对象
			try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return mqHandler;
	}
	
	
    public class MqHandler extends Handler {
		
		public MqHandler(Looper looper){
			super(looper);		
		}		

		@Override
		public void handleMessage(Message msg) {
			try {
				TcpPacket pack=(TcpPacket) msg.obj;
				if(pack!=null){
					TcpMessageHandle.createInstance(context).dispatchMessager(pack,pack.commandType);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
//			Log.e("MessageQueue", "MessageQueueMessageQueueMessageQueue  : "+msg.what);
		}		
	}	
    
    
}
